package com.hzhc.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSONObject;
import com.hzhc.common.HttpStatus;
import com.hzhc.entity.SysTokenErrorLog;
import com.hzhc.service.SysTokenErrorLogService;
import com.hzhc.utils.IpUtils;
import com.hzhc.utils.TokenUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDateTime;


/**
 * @ClassName: TokenInterceptor
 * @Description:
 * @version 1.0
 * @author: duanhm
 * @Date: 2022/01/29 22:03:52
 *
 */
public class TokenInterceptor implements HandlerInterceptor {
	private static Logger log = LoggerFactory.getLogger(TokenInterceptor.class);

	@Autowired
	private SysTokenErrorLogService tokenErrorLogService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		if (!(handler instanceof HandlerMethod)){
			return true;
		}
		String token = request.getHeader("token");
		try {
			response.setCharacterEncoding("utf-8");
			if(StrUtil.isBlank(token)){
				//token失效
				setTokenError(request,response,token);
				return false;
			}
//			if(object == null){
//				//token失效
//				setTokenError(request,response,token);
//				return false;
//			}
			boolean result = TokenUtil.verify(token);
			if (result) {
				log.info("通过拦截器");
				return true;
			}else {
				//token失效
				setTokenError(request,response,token);
				return false;
			}
		} catch (Exception e) {
			log.error(e.getMessage());
			//token失效
			setTokenError(request,response,token);
			return false;
		}
	}

	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {

	}

	private void setErrorInfo(HttpServletResponse response) throws IOException {
		JSONObject json = new JSONObject();
		json.put("success", "false");
		json.put("msg", "认证失败，未通过拦截器");
		json.put("code", HttpStatus.FORBIDDEN);
		response.setCharacterEncoding("UTF-8");
		response.setContentType("application/json; charset=utf-8");
		response.getWriter().append(json.toJSONString());
		log.info("认证失败，未通过拦截器");
	}

	private void setTokenError(HttpServletRequest request ,HttpServletResponse response,String token) throws IOException {
		//token失效
		setErrorInfo(response);
		//保存认证失败日志
		SysTokenErrorLog tokenErrorLog = new SysTokenErrorLog();
		tokenErrorLog.setClientIp(IpUtils.getIpAddr(request));
		tokenErrorLog.setCreateTime(LocalDateTime.now());
		tokenErrorLog.setOptContent("token认证失败！");
		//保存Token错误日志
		tokenErrorLogService.save(tokenErrorLog);
	}
}
